package flowcontrol.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 场景：一个线程等待多个线程执行完成，在继续下一步
 */
public class TestCountDownLatch1 {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(5);
        ExecutorService service = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            final int k = i;
            service.submit(() -> {
                try {
                    Thread.sleep(1000);
                    System.out.println("员工 " + k + "完成了工作");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    latch.countDown();
                }
            });
        }
        service.shutdown();
        System.out.println("等待所有员工完成工作");
        latch.await();
        System.out.println("所有员工已完成工作");
    }
}
